package com.example.mp3player;

import java.util.List;

import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class PlayListArrayAdapter extends ArrayAdapter<String>{
	private Context ctx;
	private int id;
	private List<String>items;

	public PlayListArrayAdapter(Context context, int textViewResourceId, List<String> objects) {
		super(context, textViewResourceId, objects);
		ctx = context;
		id = textViewResourceId;
		items = objects;
	}

	public String getItem(int i){
		return items.get(i);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(id, null);
		}

		final String item = items.get(position);

		if (item != null) {
			TextView song = (TextView) v.findViewById(R.id.SongView01);
			TextView time = (TextView) v.findViewById(R.id.TimeView01);
			
			if(song!=null)
				song.setText(getSongName(position));
			if(time!=null)
				time.setText(getSongLength(position));
		}
		return v;
	}
	
	/*	Get id3 tags from mp3-file else send file-nam	e*/
	public String getSongName(int pos){
		MediaMetadataRetriever mmr = new MediaMetadataRetriever();
		mmr.setDataSource(items.get(pos));
		if(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST).isEmpty() 
				|| mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE).isEmpty()){
			String[] tmp = items.get(pos).split("/");
			String[] file = tmp[tmp.length-1].split(".");
			String fileName = file[0];
			return fileName;
		}
		else{
			String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
			String song = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
			String tmp = artist + " - " + song;
			return tmp;
		}
	}
	
	public String getSongLength(int pos){
		MediaMetadataRetriever mmr = new MediaMetadataRetriever();
		mmr.setDataSource(items.get(pos));
		if(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) == null){
			String tmp = "00:00";
			return tmp;
		}
		else{
			int duration = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
			int minutes = (duration/1000)/60;
			int sec = duration/1000%60;
			String songLength = minutes + ":" + sec;
			return songLength;
		}
	}
}
